/*
 * StringLiteralAst.cpp
 *
 *  Created on: 19 Nov 2010
 *      Author: kn308
 */

#include <MAlice/Ast/StringLiteralAst.h>
#include <MAlice/Ast/CharacterLiteralAst.h>

#include <MAlice/Codegen.h>

namespace MAlice
{

StringLiteralAst::StringLiteralAst(const string& value) :
	mValue(value)
{
}

StringLiteralAst::~StringLiteralAst()
{
}

static inline Constant* getConstantChar(char c)
{
	return reinterpret_cast<Constant*> (CharacterLiteralAst(c).generate());
}

llvm::Value* StringLiteralAst::generate()
{
	Codegen* g = Codegen::get();

	// put all of the characters into LLVM format
	vector<Constant*> values;
	for (string::iterator i = mValue.begin(), e = mValue.end(); i != e; i++)
		values.push_back(getConstantChar(*i));

	// append null terminator
	values.push_back(getConstantChar(NULL));

	// construct the type of the string
	ArrayType* type = ArrayType::get(Type::getInt8Ty(g->getContext()),
			values.size());

	// the result is a constant array of the characters with an additional null terminator
	return ConstantArray::get(type, values);
}

}
